﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserOwnerDA : IUserOwnerDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string IS_DEFAULT = "@IS_DEFAULT";
        private string OWNER_ID = "@OWNER_ID";
        private string SQL_CHECK_USER_OWNER_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_OWNER WHERE OWNER_ID = @OWNER_ID AND USER_ID = @USER_ID ";
        private string SQL_DELETE_USER_OWNER = " DELETE FROM @_@USER_OWNER WHERE OWNER_ID = @OWNER_ID AND USER_ID = @USER_ID ";
        private string SQL_INSERT_USER_OWNER = " INSERT INTO @_@USER_OWNER ( USER_ID, OWNER_ID, IS_DEFAULT, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @USER_ID, @OWNER_ID, @IS_DEFAULT, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_USER_OWNER = " SELECT  ROWID, USER_ID, OWNER_ID, IS_DEFAULT, TS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@USER_OWNER ";
        private string SQL_UPDATE_USER_OWNER = " UPDATE @_@USER_OWNER SET IS_DEFAULT = @IS_DEFAULT, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE OWNER_ID = @OWNER_ID AND USER_ID = @USER_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";

        public bool CheckUserOwnerIDUnique(string ownerID, string userID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", ownerID), new SqlParameter("@USER_ID", userID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_OWNER_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserOwnerIDUnique(DataBase dataBase, DbTransaction tran, string ownerID, string userID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", ownerID), new SqlParameter("@USER_ID", userID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_OWNER_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserOwner(string userID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    string StrSql = " DELETE FROM @_@USER_OWNER WHERE  USER_ID = '" + userID + "'";
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.Replace("@_@", whLoginID[i]));
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserOwner(DataBase dataBase, DbTransaction tran, string userID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < whLoginID.Count; j++)
                {
                    string StrSql = " DELETE FROM @_@USER_OWNER WHERE  USER_ID = '" + userID + "'";
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.Replace("@_@", whLoginID[j]));
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserOwner(DataBase dataBase, DbTransaction tran, string ownerID, string userID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < whLoginID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", ownerID), new SqlParameter("@USER_ID", userID) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_OWNER.Replace("@_@", whLoginID[j]), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserOwnerByOwnerID(DataBase dataBase, DbTransaction tran, string ownerID, string whLoginID)
        {
            int result = 0;
            try
            {
                string StrSql = " DELETE FROM SYSADM.USER_OWNER WHERE OWNER_ID = '" + ownerID + "'";
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserOwner(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_OWNER.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserOwner(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_OWNER.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public DataSet GetAuthorizationUserByOwnerID(string ownerID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT UM.USER_ID,UM.USER_NAME, CASE LEN(ISNULL(UO.USER_ID,''))  WHEN 0 THEN 'N' ELSE 'Y' END AS PREMISSION_USER FROM SYSADM.USER_MST UM LEFT JOIN SYSADM.USER_OWNER UO ON UM.USER_ID = UO.USER_ID AND UO.OWNER_ID = '{0}'", ownerID);
            return DBHelper.ExecuteDataSet(CommandType.Text, StrSql.ToString());
        }

        public List<OwnerInfo> GetAuthorizedOwnerByUserID(string userID, string whLoginID)
        {
            List<OwnerInfo> OwnerList = new List<OwnerInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT  O.OWNER_ID,O.COMPANY,SU.IS_DEFAULT FROM {1}OWNER O  INNER JOIN   SYSADM.USER_OWNER SU ON O.OWNER_ID = SU.OWNER_ID AND O.TYPE=1 WHERE SU.USER_ID='{0}'", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                OwnerInfo ownerInfo = null;
                while (reader.Read())
                {
                    ownerInfo = new OwnerInfo(reader["owner_id"].ToString(), reader["company"].ToString(), reader["IS_DEFAULT"].ToString());
                    OwnerList.Add(ownerInfo);
                }
            }
            return OwnerList;
        }

        public OwnerInfo GetOwnerByUserID(string userID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT OWNER_ID,IS_DEFAULT FROM  SYSADM.USER_OWNER WHERE IS_DEFAULT='Y' AND USER_ID='{0}'", userID);
            OwnerInfo ownerInfo = new OwnerInfo();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                while (reader.Read())
                {
                    ownerInfo = new OwnerInfo(reader["OWNER_ID"].ToString(), "", reader["IS_DEFAULT"].ToString());
                }
            }
            return ownerInfo;
        }

        public List<OwnerInfo> GetUnauthorizedOwnerByUserID(string userID, string whLoginID)
        {
            List<OwnerInfo> OwnerList = new List<OwnerInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("   SELECT  O.OWNER_ID,O.COMPANY,''AS IS_DEFAULT  FROM {1}OWNER O  WHERE O.OWNER_ID NOT IN( SELECT OWNER_ID FROM SYSADM.USER_OWNER WHERE USER_ID='{0}') AND O.TYPE=1", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                OwnerInfo ownerInfo = null;
                while (reader.Read())
                {
                    ownerInfo = new OwnerInfo(reader["owner_id"].ToString(), reader["company"].ToString(), reader["IS_DEFAULT"].ToString());
                    OwnerList.Add(ownerInfo);
                }
            }
            return OwnerList;
        }

        public DataSet GetUserOwnerByQueryList(List<string> sqlWhere, UserOwnerQueryEntity userownerQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_OWNER.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!userownerQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, userownerQuery.CurrentPage, userownerQuery.PageSize, userownerQuery.SortField, userownerQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserOwnerByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserOwnerQueryEntity userownerQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_OWNER.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!userownerQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, userownerQuery.CurrentPage, userownerQuery.PageSize, userownerQuery.SortField, userownerQuery.SortDirection);
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public List<UserOwnerInfo> GetUserOwnerInfoByOwnerIDandUserID(string ownerID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            string sql = this.SQL_SELECT_ALL_USER_OWNER.Replace("@_@", whLoginID) + "WHERE OWNER_ID = '{0}'";
            StrSql.AppendFormat(sql, ownerID);
            List<UserOwnerInfo> userOwnerListInfo = new List<UserOwnerInfo>();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserOwnerInfo userOwnerInfo = null;
                while (reader.Read())
                {
                    DateTime CS00001;
                    userOwnerInfo = new UserOwnerInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00001 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00001 = new DateTime()));
                    userOwnerListInfo.Add(userOwnerInfo);
                }
            }
            return userOwnerListInfo;
        }

        public List<UserOwnerInfo> GetUserOwnerInfoByOwnerIDandUserID(DataBase dataBase, DbTransaction tran, string ownerID, string whLoginID)
        {
            StringBuilder StrSql = new StringBuilder();
            string sql = this.SQL_SELECT_ALL_USER_OWNER.Replace("@_@", whLoginID) + "WHERE OWNER_ID = '{0}'";
            StrSql.AppendFormat(sql, ownerID);
            List<UserOwnerInfo> userOwnerListInfo = new List<UserOwnerInfo>();
            using (IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, StrSql.ToString()))
            {
                UserOwnerInfo userOwnerInfo = null;
                while (reader.Read())
                {
                    DateTime CS00001;
                    userOwnerInfo = new UserOwnerInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00001 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00001 = new DateTime()));
                    userOwnerListInfo.Add(userOwnerInfo);
                }
            }
            return userOwnerListInfo;
        }

        public int InsertUserOwner(UserOwnerInfo userownerInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserOwner_Parameters(userownerInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_OWNER.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserOwner(DataBase dataBase, DbTransaction tran, UserOwnerInfo userOwnerInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserOwner_Parameters(userOwnerInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_OWNER.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertUserOwnerByOwnerID(DataBase dataBase, DbTransaction tran, List<UserOwnerInfo> userOwnerListInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                foreach (UserOwnerInfo userOwnerInfo in userOwnerListInfo)
                {
                    SqlParameter[] paras = this.Set_UserOwner_Parameters(userOwnerInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_OWNER.Replace("@_@", whLoginID), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserOwner_Parameters(UserOwnerInfo userOwnerInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.OWNER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.IS_DEFAULT, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userOwnerInfo.UserID;
            paramArray[1].Value = userOwnerInfo.OwnerID;
            if (!string.IsNullOrEmpty(userOwnerInfo.IsDefault))
            {
                paramArray[2].Value = userOwnerInfo.IsDefault;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userOwnerInfo.CreatedBy;
            paramArray[4].Value = userOwnerInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserOwner(UserOwnerInfo userOwnerInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserOwner_Parameters(userOwnerInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_OWNER.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserOwner(DataBase dataBase, DbTransaction tran, UserOwnerInfo userOwnerInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserOwner_Parameters(userOwnerInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_OWNER.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

